package message_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

type MessageRecordRequest struct {
	UserID uint `json:"user_id" binding:"required" msg:"请选择查询用户ID"`
}

func (MessageApi) MessageRecord(c *gin.Context) {
	var cr MessageRecordRequest
	if err := c.ShouldBindJSON(&cr); err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	claims, _ := c.Get("user")
	user := claims.(*utils.UserClaims)

	if user.UserID == cr.UserID {
		http.FailWithMessage("请选择正确用户", c)
		return
	}

	// 点开消息记录, 里面每条消息都会从未读改成已读
	err := common.DB.Model(new(models.MessageModel)).Debug().Where("send_user_id = ? AND rev_user_id = ?", user.UserID, cr.UserID).Update("is_read", 1).Error
	if err != nil {
		common.Log.Error(err.Error())
	}

	messageList := make([]*models.MessageModel, 0)
	_messageList := make([]*models.MessageModel, 0)
	err = common.DB.Order("created_at ASC").Find(&_messageList, "send_user_id = ? OR rev_user_id = ?", user.UserID, user.UserID).Error
	if err != nil {
		common.Log.Error(err.Error())
		http.FailWithMessage("聊天记录查询失败", c)
		return
	}
	for _, model := range _messageList {
		if model.SendUserID == cr.UserID || model.RevUserID == cr.UserID {
			messageList = append(messageList, model)
		}
	}
	http.IsOkWithData(messageList, c)
}
